﻿using System;
using System.Collections.Generic;
using System.Text;
using reactiveBT.Utilities;

namespace reactiveBT.BT
{
    /// <summary>
    /// 根分支节点
    /// 具有单Tick多节点特性，单次Tick一定找到返回Continue的子节点，并返回Continue。若找不到则返回Success
    /// Root节点阻止Abort信息向上传播，如果该子树挂起，则返回Failure
    /// TODO 考虑一下优化挂起信息
    /// </summary>
    public class Root : Branch
    {
        //在root节点中引入标记位，提高性能
        public bool isTerminated = false;
        protected override void ResetSelf()
        {
            base.ResetSelf();
        }
        public override BTState Tick(int BTid)
        {
            if (needToReset)
            {
                this.ResetSelf();
                base.ResetChildren();
                needToReset = false;
            }
            if (isTerminated)
            {
                return BTState.Failure;
            }
            //root节点单帧一定找到能执行的子节点,考虑将此特性引入其他节点中
            while(true)
            {
                var result = children[activeChild].Tick(BTid);
                switch (result)
                {
                    case BTState.Continue:
                        return BTState.Continue;
                    case BTState.Abort:
                        isTerminated = true;
                        return BTState.Failure;
                    default:
                        activeChild++;
                        if (activeChild == children.Count)
                        {
                            needToReset = true;
                            return BTState.Success;
                        }
                        continue;
                }
            }
        }
    }
}
